/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.ipleiria.plp.ui;

import de.enough.polish.ui.ChoiceGroup;
import de.enough.polish.ui.ChoiceItem;
import de.enough.polish.ui.Command;
import de.enough.polish.ui.CommandListener;
import de.enough.polish.ui.Displayable;
import de.enough.polish.ui.Item;
import de.enough.polish.ui.ItemCommandListener;
import de.enough.polish.ui.ItemStateListener;
import de.enough.polish.ui.List;
import de.enough.polish.ui.StringItem;
import de.enough.polish.ui.TabbedForm;
import de.enough.polish.ui.TextField;
import de.enough.polish.ui.gaugeviews.ImagesGaugeView;
import de.enough.polish.util.ArrayList;
import de.enough.polish.util.Locale;
import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.location.Coordinates;
import pt.ipleiria.plp.BlackSpotterMidlet;
import pt.ipleiria.plp.threads.CallbackRetrievePos;
import pt.ipleiria.plp.ImagePath;
import pt.ipleiria.plp.Lixeiras.Lixeira;
import pt.ipleiria.plp.Utils;
import pt.ipleiria.plp.stub.WasteVolume;

/**
 *
 * @author Filipe
 */
public abstract class EventoScreen extends TabbedForm implements CommandListener,
        CallbackRetrievePos, ItemStateListener, ItemCommandListener {

    /**
     * @param aTabNames the tabNames to set
     */
    public static void setTabNames(String[] aTabNames) {
        tabNames = aTabNames;
    }

    /**
     * @param aCatLixeira the catLixeira to set
     */
    public static void setCatLixeira(String[] aCatLixeira) {
        catLixeira = aCatLixeira;
    }
    private OnHold hold;
    private BlackSpotterMidlet midlet;
    private Coordinates coords = null;
    private static String tabNames[] = {Locale.get("tab.geral"), Locale.get("tab.info"),
        Locale.get("tab.imag"), Locale.get("tab.cat")};
    /*private static String impactChoices[] = {Locale.get("newEv.impPos"),
    Locale.get("newEv.impNeg")};
    private static String catGeral[] = {Locale.get("class.lixeira"), Locale.get("class.ar"),
    Locale.get("class.agua"), Locale.get("class.radioativo"), Locale.get("class.terrmico"),
    Locale.get("class.outros"), Locale.get("class.tratamento"), Locale.get("class.luminusidade"),
    Locale.get("class.solo")};*/
    private static String catLixeira[] = {Locale.get("cats.org"), Locale.get("cats.plast"),
        Locale.get("cats.papel"), Locale.get("cats.met"), Locale.get("cats.vidro"),
        Locale.get("cats.mad"), Locale.get("cats.bigVol"), Locale.get("cats.oleo"),
        Locale.get("cats.constr"), Locale.get("cats.auto"), Locale.get("cats.perig")};
    private static String tamanhos[] = {Locale.get("newEv.peq"), Locale.get("newEv.med"),
        Locale.get("newEv.grd")};
    //private Command cmdConc = new Command(Locale.get("cmd.Concluir"), Command.OK, 1);
    private Command cmdProx = new Command(Locale.get("cmd.Proximo"), Command.CANCEL, 2);
    private Command cmdExit = new Command(Locale.get("cmd.Sair"), Command.EXIT, 2);
    //private Command cmdAnt = new Command(Locale.get("cmd.Anterior"), Command.EXIT, 2);
    private Command cmdSim = new Command(Locale.get("cmd.Sim"), Command.OK, 2);
    private Command cmdNao = new Command(Locale.get("cmd.Nao"), Command.BACK, 2);
// <editor-fold defaultstate="collapsed" desc="TAB 0">
    //#style itemInput
    private TextField title = new TextField(Locale.get("newEv.titlo"), "", 25, TextField.ANY);
    //#style itemInput
    private TextField pos = new TextField(Locale.get("newEv.pos"), "", 25, TextField.ANY);
    //#style itemButton
    private StringItem addPos = new StringItem("", Locale.get("cmd.obter"), StringItem.BUTTON);
    private Command cmdObt = new Command(Locale.get("cmd.obter"), Command.ITEM, 1);
    private StringItem gpsoff = new StringItem("", Locale.get("mensagem.posHelp"));
    //#style itemInput
    private TextField descBox = new TextField(Locale.get("newEv.desc"), "", 255,
            TextField.ANY);
    /* NAO ESTA IMPLEMENTADO POIS NOS WEBSERVICES APENAS PERMITEM A CATEGORIA LIXEIRAS
    private ChoiceGroup impacto = new ChoiceGroup(Locale.get("newEv.imp"),
    ChoiceGroup.EXCLUSIVE, impactChoices, null);

    private int catEscolhida = 0;

    private ChoiceGroup cat = new ChoiceGroup(Locale.get("newEv.cat"),
    ChoiceGroup.POPUP, catGeral, null);
     */
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="TAB 1">
    //#style horizontalChoice
    private ChoiceGroup tam = new ChoiceGroup(Locale.get("newEv.tam"),
            ChoiceGroup.POPUP, tamanhos, null);
    //#style multipleChoice
    private ChoiceGroup catLix = new ChoiceGroup(Locale.get("cats.title"),
            ChoiceGroup.MULTIPLE, catLixeira, null);
    //#style itemInput
    private TextField vol = new TextField(Locale.get("newEv.volume"), "", 6,
            TextField.ANY);
    //#style itemInput
    private TextField estVolunt = new TextField(Locale.get("newEv.numero"), "", 6,
            TextField.NUMERIC);
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="TAB 2">
    //#style itemButton
    private StringItem addFoto = new StringItem("", Locale.get("cmd.add"), StringItem.BUTTON);
    private Command cmdAddFoto = new Command(Locale.get("cmd.add"), Command.ITEM, 1);
    //#style itemButton
    private StringItem remFoto = new StringItem("", Locale.get("cmd.del"), StringItem.BUTTON);
    private Command cmdRemFoto = new Command(Locale.get("cmd.del"), Command.ITEM, 1);
    private ChoiceGroup fotosList;
    private boolean estBool = false;
    private ArrayList<ImagePath> images;
    private boolean toClear = false;
    private TextField fotosExistList = null;
    //#style itemButton
    private StringItem remAllFotos = new StringItem("", Locale.get("cmd.delAll"), StringItem.BUTTON);
    private Command cmdRemAllFotos = new Command(Locale.get("cmd.del"), Command.ITEM, 1);
    //#style itemButton
    private StringItem cancelRemAll = new StringItem("", Locale.get("cmd.Cancelar"), StringItem.BUTTON);
    private Command cmdCancRemAllFotos = new Command(Locale.get("cmd.Cancelar"), Command.ITEM, 1);
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="TAB 3">
    private Vector tags;
    //#style itemInput
    private TextField novaTag = new TextField(Locale.get("newEv.nTag"), "", 20, TextField.ANY);
    //#style itemButton
    private StringItem addTag = new StringItem("", Locale.get("cmd.add"), StringItem.BUTTON);
    private Command cmdAddTag = new Command(Locale.get("cmd.add"), Command.ITEM, 1);
    //#style itemButton
    private StringItem remTag = new StringItem("", Locale.get("cmd.del"), StringItem.BUTTON);
    private Command cmdRemTag = new Command(Locale.get("cmd.del"), Command.ITEM, 1);
    private ChoiceGroup tagsList;
    private boolean estBool2 = false;
// </editor-fold>

    public EventoScreen(BlackSpotterMidlet midlet, String title, String[] fotosExistList) {
        //#style tabbedForm
        super(title, tabNames, null);

        if (fotosExistList != null) {
            System.out.println("Foto ExistList Size: " + fotosExistList.length);
            this.fotosExistList = new TextField("", "", 1000, TextField.UNEDITABLE);

            for (int i = 0; i < fotosExistList.length; i++) {
                System.out.println("Foto: " + fotosExistList[i]);
                this.fotosExistList.setString(fotosExistList[i] + "\n");
            }
        }

        this.midlet = midlet;
        this.setCommandListener(this);
        this.setItemStateListener(this);
        addButtonCommands();
        this.addCommand(cmdProx);
        this.addCommand(cmdExit);

        this.images = new ArrayList<ImagePath>();

        tags = midlet.getApp().getAppData().getTags();
        if (!tags.isEmpty()) {
            //#style multipleChoice
            tagsList = new ChoiceGroup("",
                    ChoiceGroup.MULTIPLE, midlet.getApp().getAppData().getTagsString(), null);
        }

    }

    private void addButtonCommands() {
        addPos.setDefaultCommand(cmdObt);
        addFoto.setDefaultCommand(cmdAddFoto);
        remFoto.setDefaultCommand(cmdRemFoto);
        remAllFotos.setDefaultCommand(cmdRemAllFotos);
        cancelRemAll.setDefaultCommand(cmdCancRemAllFotos);
        addTag.setDefaultCommand(cmdAddTag);
        remTag.setDefaultCommand(cmdRemTag);
    }

    public void commandAction(Command c, Displayable d) {
        System.out.println("Command: " + c.getLabel());
        if (c == cmdRemAllFotos) {
            this.delete(2, fotosExistList);
            this.delete(2, remAllFotos);
            this.append(2, cancelRemAll);

        } else if (c == cmdCancRemAllFotos) {

            this.delete(2, cancelRemAll);
            this.append(2, fotosExistList);
            this.append(2, remAllFotos);


        }

    }

    public void commandAction(Command c, Item item) {

        System.out.println("Command: " + c.toString());
        System.out.println("Item: " + item.getLabel());

        if (c == cmdObt) {

            getMidlet().getApp().getCords(this);
            //pos.removeCommand(cmdObt);
            hold = new OnHold(midlet, this);
            midlet.getDisplay().setCurrent(hold);

        } else if (c == cmdAddTag && novaTag.getString().length() > 0) {

            tags.addElement(novaTag.getString());
            if (tagsList == null) {
                tagsList = new ChoiceGroup("", ChoiceGroup.MULTIPLE);
                this.append(3, tagsList);
            }
            tagsList.append(novaTag.getString(), null);
            novaTag.setString("");

        } else if (c == cmdAddFoto) {
            AdicionarFotografia adicionar = new AdicionarFotografia(this);
            getMidlet().getDisplay().setCurrent(adicionar);
        } else if (c == cmdRemFoto) {

            String[] selc = Utils.getSelectedStrings(fotosList);

            fotosList.clear();

            Object[] temp = images.toArray();
            for (int j = 0; j < selc.length; j++) {
                for (int i = 0; i < temp.length; i++) {

                    if (((ImagePath) temp[i]).getTitle().compareTo(selc[j]) == 0) {
                        images.remove((ImagePath) temp[i]);
                    }
                }
            }
            temp = images.toArray();

            for (int i = 0; i < temp.length; i++) {

                fotosList.append(((ImagePath) temp[i]).getTitle(), null);
            }
            this.delete(2, remFoto);
            /*
            int selected[] = Utils.getSelectedIndexes(fotosList);
            //tem de ser de trás para frente para nao haver problemas
            //se não pode remover items errados
            for (int i = selected.length - 1; i >= 0; i--) {
            fotosList.delete(selected[i]);
            if (selected.length == 1) {
            this.delete(2, remFoto);
            }
            }
             */
        } else if (c == cmdRemTag) {

            int selected[] = Utils.getSelectedIndexes(tagsList);
            //tem de ser de trás para frente para nao haver problemas
            //se não pode remover items errados
            for (int i = selected.length - 1; i >= 0; i--) {
                tags.removeElementAt(i);
                tagsList.delete(selected[i]);
                if (selected.length == 1) {
                    this.delete(3, remTag);
                }
            }
        } else if (c == cmdRemAllFotos) {

            this.delete(2, fotosExistList);
            this.delete(2, remAllFotos);
            this.append(2, cancelRemAll);

        } else if (c == cmdCancRemAllFotos) {

            this.delete(2, cancelRemAll);
            this.append(2, fotosExistList);
            this.append(2, remAllFotos);

        }
    }

    public void returnCoordinates(Coordinates coords) {
        if (coords != null) {
            this.coords = coords;
            pos.setString(coords.getLatitude() + "," + coords.getLongitude());
            pos.addCommand(cmdObt);
        }
        hold.finishWait();
    }

    public void createTabs(boolean zero) {
        if (zero) {
            createTabZero();
        }
        createTabOne();
        createTabTwo();
        createTabThree();
    }

    private void createTabZero() {
        this.append(0, title);
        if (getMidlet().getApp().hasGps() || getMidlet().getApp().acquireGPS()) {


            addPos.addCommand(cmdObt);
            addPos.setItemCommandListener(this);
            this.append(0, pos);
            this.append(0, addPos);

        } else {
            this.append(0, pos);
            this.append(0, gpsoff);
        }
        this.append(0, descBox);
        //this.append(0, impacto);
        //this.append(0,getCat());


    }

    private void createTabOne() {
        this.append(1, tam);
        this.append(1, vol);
        this.append(1, estVolunt);
        this.append(1, catLix);
    }

    private void createTabTwo() {
        addFoto.addCommand(cmdAddFoto);
        addFoto.setItemCommandListener(this);
        this.append(2, addFoto);
        remFoto.addCommand(cmdRemFoto);
        remFoto.setItemCommandListener(this);
        remAllFotos.addCommand(cmdRemAllFotos);
        remAllFotos.setItemStateListener(this);
        cancelRemAll.addCommand(cmdCancRemAllFotos);
        cancelRemAll.setItemCommandListener(this);

        if (fotosExistList != null) {
            if (!isToClear()) {
                this.append(2, fotosExistList);
                this.append(2, remAllFotos);
            } else {

                this.append(cancelRemAll);

            }
        }

        if (fotosList != null) {
            this.append(2, fotosList);
            if (Utils.getSelectedIndexes(fotosList).length != 0) {
                this.append(2, remFoto);
            }

        }

    }

    private void createTabThree() {


        //#style itemInput
        this.append(3, novaTag);
        addTag.addCommand(cmdAddTag);
        addTag.setItemCommandListener(this);
        this.append(3, addTag);
        remTag.addCommand(cmdRemTag);
        remTag.setItemCommandListener(this);
        if (tagsList != null) {
            this.append(3, tagsList);

            if (Utils.getSelectedIndexes(tagsList).length > 0) {

                this.append(3, remTag);
            }
        }



    }

    public void itemStateChanged(Item item) {
        /* IMPLEMENTADO DESNECESSARIAMENTE JA QUE O WEBSERVICE NAO PERMITE
        if (item == getCat()) {
        if (getCatEscolhida() == 0 && getCat().getSelectedIndex() != 0) {
        catEscolhida = getCat().getSelectedIndex();
        this.removeTab(1);
        }

        if (getCatEscolhida() != 0 && getCat().getSelectedIndex() == 0) {
        catEscolhida = getCat().getSelectedIndex();
        this.addNewTab(1, Locale.get("tab.info"), null);
        createTabOne();
        }

        } else*/ if (item == fotosList) {
            if (Utils.getSelectedIndexes(fotosList).length > 0 && !estBool) {
                this.append(2, remFoto);
                estBool = true;
            } else if (Utils.getSelectedIndexes(fotosList).length == 0 && estBool) {
                this.delete(2, remFoto);
                estBool = false;
            }
        } else if (item == tagsList) {
            if (Utils.getSelectedIndexes(tagsList).length > 0 && !estBool2) {
                this.append(3, remTag);
                estBool2 = true;
            } else if (Utils.getSelectedIndexes(tagsList).length == 0 && estBool2) {
                this.delete(3, remTag);
                estBool2 = false;
            }
        }
    }

    public void returnFromPhoto(ImagePath[] photos) {

        if (photos != null) {
            System.out.println("OI photos size: " + photos.length);
            if (fotosList == null) {
                fotosList = new ChoiceGroup("", ChoiceGroup.MULTIPLE);
            }

            images.addAll(photos);
            //evitar duplicados
            fotosList.clear();

            Object[] temp = images.toArray();

            for (int i = 0; i < temp.length; i++) {

                fotosList.append(((ImagePath) temp[i]).getTitle(), null);
                this.append(2, fotosList);
            }

        }

        this.setCommandListener(this);
        getMidlet().getDisplay().setCurrent(this);
    }

    /**
     * @return the midlet
     */
    public BlackSpotterMidlet getMidlet() {
        return midlet;
    }

    /**
     * @return the cmdProx
     */
    public Command getCmdProx() {
        return cmdProx;
    }

    /**
     * @return the cmdExit
     */
    public Command getCmdExit() {
        return cmdExit;
    }

    /**
     * Validates the fields
     */
    public int validateFields() {

        if (pos.getString().length() == 0 || getPos() == null) {
            return 1;
        }
        if (descBox.getString().length() == 0) {
            return 2;
        }
        //if (getCatEscolhida() == 0 && Utils.getSelectedIndexes(getCatLix()).length == 0) {
        if (Utils.getSelectedIndexes(catLix).length == 0) {
            return 3;
        }
        if (Utils.getSelectedIndexes(tagsList).length == 0) {
            return 4;
        }
        if (vol.getString().length() == 0) {
            return 5;
        }
        if (estVolunt.getString().length() == 0) {
            return 6;
        }

        return 0;
    }

    /**
     * Returns the tile of the lixeira being edited / created
     * @return the title
     */
    public String getLixTitle() {

        return title.getString();
    }

    /**
     * @return the pos element 0 is lat element 1 is long
     */
    public double[] getPos() {

        double[] position = new double[2];

        String[] strs = Utils.split(pos.getString(), ",");

        if (strs.length != 2) {
            return null;
        }
        try {
            position[0] = Double.parseDouble(strs[0]);
            position[1] = Double.parseDouble(strs[1]);
        } catch (NumberFormatException ex) {
            return null;
        }
        return position;
    }

    /**
     * @return the descBox
     */
    public String getDescBox() {
        return descBox.getString();
    }

    /**
     * @return the tam
     */
    public WasteVolume getTam() {
        WasteVolume ret;
        switch (tam.getSelectedIndex()) {
            case 0:
                ret = WasteVolume.Small;
                break;
            case 1:
                ret = WasteVolume.Medium;
                break;
            case 2:
                ret = WasteVolume.Large;
                break;
            default:
                ret = null;
                break;
        }
        return ret;
    }

    /**
     * This function converts the categories the user made
     * to the global format used by the webservice
     * @return the selected categories in the webservice format
     */
    public String[] getCatLix() {

        int[] selected = Utils.getSelectedIndexes(catLix);

        if (selected.length == 0) {
            return null;
        }
        String[] cats = new String[selected.length];

        for (int i = 0; i < selected.length; i++) {

            cats[i] = Lixeira.CATEGORYS[selected[i]];
            System.out.println("Cat: " + i + " " + cats[i]);
        }


        return cats;
    }

    /**
     * @return the fotos
     */
    public ImagePath[] getFotos() {
        Object[] temp = images.toArray();
        ImagePath[] returning = new ImagePath[temp.length];

        for (int i = 0; i < temp.length; i++) {
            returning[i] = (ImagePath) temp[i];
        }

        return returning;
    }

    /**
     * @return the tagsList
     */
    public String[] getTagsList() {
        return Utils.getSelectedStrings(tagsList);
    }

    /**
     * @return number of volunteers
     */
    public int getNumVolunteers() {
        return Integer.parseInt(estVolunt.getString());
    }

    /**
     * @return the volume
     */
    public String getEstVolume() {
        return vol.getString();
    }

    /**
     * @return the toClear
     */
    public boolean isToClear() {
        return toClear;
    }

    /**
     * @param title the title to set
     */
    public void setLixTitle(String title) {
        this.title.setString(title);
    }

    /**
     * make the lixeira title unedited
     */
    public void setLixTitleBlocked() {
        this.title.setConstraints(TextField.UNEDITABLE);
    }

    /**
     * @param pos the pos to set
     */
    public void setPos(String pos) {
        this.pos.setString(pos);
    }

    /**
     * @param descBox the descBox to set
     */
    public void setDescBox(String descBox) {
        this.descBox.setString(descBox);
    }

    /**
     * @param tam the tam to set
     */
    public void setTam(WasteVolume tam) {
        System.out.println("WasteVolume: " + tam.getValue());
        if (tam.equals(WasteVolume.Small)) {
            this.tam.setSelectedIndex(0, true);
            System.out.println("Escolhido: 0");
        } else if (tam.equals(WasteVolume.Medium)) {
            this.tam.setSelectedIndex(1, true);
            System.out.println("Escolhido: 1");
        } else if (tam.equals(WasteVolume.Large)) {
            this.tam.setSelectedIndex(2, true);
            System.out.println("Escolhido: 2");
        }

    }

    /**
     * @param catLix the catLix to set
     */
    public void setCatLix(String[] cats) {
        for (int i = 0; i < cats.length; i++) {

            for (int j = 0; j < Lixeira.CATEGORYS.length; j++) {
                if (cats[i].equals(Lixeira.CATEGORYS[j])) {
                    catLix.setSelectedIndex(j, true);
                }
            }

        }
    }

    /**
     * @param vol the vol to set
     */
    public void setVol(String vol) {
        this.vol.setText(vol);
    }

    /**
     * @param estVolunt the estVolunt to set
     */
    public void setEstVolunt(int estVolunt) {
        this.estVolunt.setText(Integer.toString(estVolunt));
    }

    /**
     * @param toClear the toClear to set
     */
    public void setToClear(boolean toClear) {
        this.toClear = toClear;
    }

    /**
     * @param tagsList the tagsList to set
     */
    public void setTagsList(String[] tags) {

        for (int i = 0; i < tags.length; i++) {

            boolean exists = false;
            Enumeration enume = this.tags.elements();
            int j = 0;
            while (enume.hasMoreElements()) {
                if (((String) enume.nextElement()).equals(tags[i])) {
                    tagsList.setSelectedIndex(j, true);
                    exists = true;
                    break;
                }
            }
            if (!exists) {
                this.tags.addElement(tags[i]);
                int temp = this.tagsList.append(tags[i], null);
                this.tagsList.setSelectedIndex(temp, true);
            }
        }
    }

    /**
     * @return the cmdSim
     */
    public Command getCmdSim() {
        return cmdSim;
    }

    /**
     * @return the cmdNao
     */
    public Command getCmdNao() {
        return cmdNao;
    }
}

